package com.ruoyi.common.utils.prometheus;

import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.constant.HostConstant;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.CacheUtils;
import com.ruoyi.common.utils.agent.AgentRestUtil;
import com.ruoyi.common.utils.http.RestUtils;
import com.ruoyi.common.utils.pushgateway.PushGatewayUtils;
import io.jsonwebtoken.lang.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;


public class PrometheusUtils {
    private static final Logger log = LoggerFactory.getLogger(PrometheusUtils.class);
    private static final String QUERY_RANGE = "/api/v1/query_range";
    private static final String QUERY_INSTANT = "/api/v1/query";
    private static final String QUERY_SERIES = "/api/v1/series";

    public static Map queryRange(PromQLQueryVo queryVo){
        final String url= CacheUtils.get(CacheConstants.SYS_CONFIG_KEY,"prometheus.url",String.class)+QUERY_RANGE;
        Map<String,String> metrics = HostConstant.HOST_METRICS.get(queryVo.getQuery());
        if(Collections.isEmpty(metrics)){
            throw new ServiceException("指标名称参数缺失");
        }
        //获取指标任务
        Map metricsMap = new HashMap();
        Map<String,Object> params = queryVo.buildRangeQuery();
        List<CompletableFuture> futures = new ArrayList<>();
        metrics.forEach((key,promQL) ->{
            CompletableFuture<Void> future = CompletableFuture.runAsync(()->{
                Map<String,Object> queryParams = new HashMap<>();
                queryParams.putAll(params);
                queryVo.buildPromQL(promQL,queryParams);
                RestTemplate template = RestUtils.getRestTemplate();
                String prometheusUrl = url+"?query={query}&start={start}&end={end}&step={step}";
                Map result = template.getForObject(prometheusUrl,Map.class,queryParams);
                if("success".equals(result.get("status"))){
                    metricsMap.put(key,result.get("data"));
                }
            });
            futures.add(future);
        });
        //等待所有任务执行完成
        CompletableFuture<Void> all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
        all.join();
        return  metricsMap;
    }
}
